import { useState, useEffect } from 'react';
import { message } from 'antd';
import { find } from 'lodash';
import CommonLoading from '@/components/CommonLoading';
import BeforePrintModal from './BeforePrintModal';
import PrintSelectModal from './PrintSelectModal';
import Api from '../../service';

export default ({ type, selectKeys, orderList, handleSavaPrint, handleOk, handleCancel }) => {

  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);

  useEffect(() => {
    getPrintDataFunc();
  }, [])

  const getPrintDataFunc = async () => {
    const systemNos = orderList.filter(v => selectKeys.includes(v.id)).map(v => v.sn);
    setLoading(true);
    const { success, data } = await Api.getPrintDataOp({ systemNos, printPageType: 0 });
    setLoading(false);
    if (success) {
      if (!data?.length) {
        handleCancel();
        return message.info('暂未获取到打印数据。');
      }
      const needConfirm = type == 2 && data?.length > 1;
      setVisible(needConfirm ? 1 : 2);
      setData(data);
    } else {
      handleCancel();
    }
  }

  const BeforePrintModalProps = {
    handleCancel,
    nums: data.length,
    handleOk() {
      setVisible(2);
    },
  }

  const PrintSelectModalProps = {
    type,
    sourceData: data,
    len: selectKeys?.length,
    handleOk,
    handleCancel,
    handleSavaPrint() {
      const printData = [];
      // console.log(filteredPageData, data)
      let nums = 0;
      for (let i = 0; i < data.length; i++) {
        const items = data[i]?.items || [];
        for (let j = 0; j < items?.length; j++) {
          const printLogisticsList = items[j].printLogisticsList || [];
          for (let k = 0; k < printLogisticsList?.length; k++) {
            printData.push({
              ...printLogisticsList[k],
              printer: items[j].printer
            })
            nums++;
          }
        }
      }
      console.log(printData, nums)
      handleSavaPrint(printData);
    },
  }

  return (<>
    {visible == 1 && <BeforePrintModal {...BeforePrintModalProps} />}
    {visible == 2 && <PrintSelectModal {...PrintSelectModalProps} />}
    <CommonLoading loading={loading} />
  </>)
}